package com.zjxny.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zjxny.exception.TrafficException;
import com.zjxny.model.AccountInfo;
import com.zjxny.model.CarInfo;
import com.zjxny.service.CarInfoService;
import com.zjxny.service.TrafficService;
import com.zjxny.service.WxCpZjService;
import com.zjxny.vo.TrafficVO;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import xyz.erupt.jpa.dao.EruptDao;
import xyz.erupt.upms.annotation.EruptLoginAuth;

@RestController
@RequestMapping("/api")
public class ApiController {
	@Resource
	WxCpZjService wxCpZjService;
	
	@Resource
	CarInfoService carInfoService;
	
	@Resource
	private EruptDao eruptDao;
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	@Resource
	private TrafficService trafficService;

	@GetMapping("/carinfo/vehqrcode/{xh}")
	@EruptLoginAuth
//    @EruptRecordOperate("登录可调用") //记录操作日志，可不定义
    public String carQr(@PathVariable(name="xh") String xh) {
		CarInfo carInfo = eruptDao.queryEntity(CarInfo.class,"xh="+xh);
		if(carInfo==null) {
			return null;
		}
		
		AccountInfo accountInfo = carInfo.getAccountInfo();
		try {
			String responseBody = carInfoService.vehqrcode(accountInfo, carInfo.getHphm());
		
			System.err.println(responseBody);
				
			JSONObject response = JSONUtil.parseObj(responseBody);
			if(response.getInt("code")==200) {
				return response.getByPath("$.data.qrcode",String.class);
			}
		} catch (TrafficException e) {
			e.printStackTrace();
			if(StrUtil.isNotBlank(e.getToUser())) {				
				wxCpZjService.sendNotifyMessage(e.getToUser(),String.format("%s会话过期,请及时处理!", e.getAccountName()));
			}
		}
		return "";
    }
	
	//isOperation
	@GetMapping("/carinfo/traffic/{xh}")
	@EruptLoginAuth
    public List<TrafficVO> trafficQuery(@PathVariable(name="xh") String xh) {
		CarInfo carInfo = eruptDao.queryEntity(CarInfo.class,"xh="+xh);
		List<TrafficVO> traffics = new ArrayList<TrafficVO>();
		if(carInfo==null) {
			return null;
		}
//		System.err.println(JSONUtil.toJsonPrettyStr(carInfo));
		try {
			if(carInfo.getIsOperation()) {
//				System.err.println("--001");
				traffics = trafficService.getOperationTrafficList(carInfo);
			} else {
//				System.err.println("---002");
				traffics = trafficService.getTrafficList(carInfo);
			}
//			System.err.println(JSONUtil.toJsonPrettyStr(traffics));
		} catch (TrafficException e) {
			e.printStackTrace();
			if(StrUtil.isNotBlank(e.getToUser())) {				
				wxCpZjService.sendNotifyMessage(e.getToUser(),String.format("%s会话过期,请及时处理!", e.getAccountName()));
			}
		}
		return traffics;
    }
}
